package com.ghca.myinfo.market.services.impl;

import com.ghca.myinfo.market.entities.TenderNotice;
import com.ghca.myinfo.market.repositories.TenderNoticeRepository;
import com.ghca.myinfo.market.services.TenderNoticeService;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/2/4.
 */
@Service
public class TenderNoticeServiceImpl implements TenderNoticeService {

    @Autowired
    private TenderNoticeRepository tenderNoticeRepository;

    @Override
    public Page<TenderNotice> list(TenderNotice tenderNotice, Pageable pageable) {
        Specification<TenderNotice> specification = new Specification<TenderNotice>() {
            @Override
            public Predicate toPredicate(Root<TenderNotice> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if(tenderNotice!=null) {
                    if (tenderNotice.getStartDate() != null && tenderNotice.getEndDate()!=null) {
                        predicates.add(cb.greaterThan(root.get("startDate"), tenderNotice.getStartDate()));

                    }
                }
                predicates.add(cb.greaterThanOrEqualTo(root.get("endDate"), new Date()));
                return cb.and(predicates.toArray(new Predicate[0]));
            }
        };

        return tenderNoticeRepository.findAll(specification, pageable);
    }
}
